package com.vgulu.server.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangchunsee on 16/1/27.
 */
public class Utils {
    public static String getCookieValue(HttpServletRequest request,String key){
        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        Cookie cookie = null;
        if (cookies!=null){
            for(Cookie c : cookies){
                if (c.getName().equals(key)){
                    cookie=c;
                    break;
                }
            }
        }
        return cookie==null?null:cookie.getValue();
    }

    public static String formatDate(Date date, String format){
        FastDateFormat dateFormat = FastDateFormat.getInstance(format);
        return dateFormat.format(date);
    }

    public static String dateToStr(Date date){
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static boolean isBlank(String content) {
        if (content==null||content.trim().isEmpty()){
            return true;
        }else {
            return false;
        }
    }

    public static int transToFen(double yuan){
        return (int)((yuan+0.0001)*100);
    }

    public static boolean isUInt(String str){
        Matcher matcher = Pattern.compile("^-?[1-9]\\d*$").matcher(str);
        return matcher.find();
    }

    public static boolean isInt(String str){
        Matcher matcher = Pattern.compile("^-?[1-9]\\d*$").matcher(str);
        return matcher.find();
    }

    public static boolean isMobile(String str){
        Matcher matcher = Pattern.compile("^1[3|4|5|7|8][0-9]\\d{4,8}$").matcher(str);
        return matcher.find();
    }

    public static Long[] parseDure(String str){
        if (StringUtils.isEmpty(str)){
            return null;
        }
        String[] ls = str.split(":");
        if (ls.length!=2){
            return null;
        }
        Long[] ret = new Long[2];
        if (!StringUtils.isEmpty(ls[0])){
            ret[0]=Long.parseLong(ls[0]);
        }
        if (!StringUtils.isEmpty(ls[1])){
            ret[1]=Long.parseLong(ls[1]);
        }
        return ret;
    }

    public static long[] parseDure(String str,long default0,long default1){
        Long[] one = parseDure(str);
        if(one==null){
            return new long[]{default0,default1};
        }
        long[] ret = new long[2];
        ret[0]=one[0]==null?default0:one[0];
        ret[1]=one[1]==null?default1:one[1];
        return ret;
    }

}
